package com.zbu.common.security.service;

import cn.hutool.core.lang.UUID;
import com.zbu.common.core.domain.LoginUser;
import com.zbu.common.core.utils.JwtUtils;
import com.zbu.common.core.constants.CacheConstants;
import com.zbu.common.core.constants.JwtConstants;
import com.zbu.common.core.enums.UserIdentity;
import com.zbu.common.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
//操作用户登录令牌
public class TokenService {
    @Resource
    RedisService redisService;
    public String createToken(Long userId,String secret,Integer identity,String nickName,String headImage){
        Map<String,Object> claims=new HashMap<>();
        String userKey= UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID,userId);
        claims.put(JwtConstants.LOGIN_USER_KEY,userKey);
        String token= JwtUtils.createToken(claims,secret);
        //第三方机制中存储敏感信息

        //身份认证具体要存储那些信息 redis表明用户身份字段 identity 1普通用户 2管理用户

        //使用什么样子的数据结构 String   key value String hash
        //key必须唯一使用uuid使用hutool必须唯一的原因是为了避免存入redis的时候被覆盖

        String key= CacheConstants.LOGIN_TOKEN_KEY+userKey;
        LoginUser loginUser=new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(key,loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }
    //在身份认证之后在调用控制层之前调用
    public void extendToken(Claims claims){
        String userKey=getUserKey(claims);
        if(userKey==null){
            return;
        }
        String tokenKey=CacheConstants.LOGIN_TOKEN_KEY+userKey;
        Long expire=redisService.getExpire(tokenKey,TimeUnit.MINUTES);
        if(expire!=null&&expire<CacheConstants.REFRESH_TIME){
            redisService.expire(tokenKey,CacheConstants.EXP,TimeUnit.MINUTES);
        }
    }
    public  Long getUserId(String token,String secret){
        Claims claims;
        try{
            claims=JwtUtils.parseToken(token,secret);
            if(claims==null){
                log.error("解析token出现异常{}",token);
                return null;
            }
        }catch (Exception e){
            log.error("解析token出现异常",token,e);
            return null;
        }
        return Long.valueOf(JwtUtils.getUserId(claims));
    }
    public LoginUser getLoginUser(String token,String secret) {
       String userKey=getUserKey(token,secret);
       if(userKey==null){
           return null;
       }
       return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);

    }
    public boolean deleteLoginUser(String token, String secret) {
        String userKey=getUserKey(token,secret);
        if(userKey==null){
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }
    private String getTokenKey(String userKey) {
        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }
    private String getUserKey(String token ,String secret){
        Claims claims;
        try{
            claims=JwtUtils.parseToken(token,secret);
            if(claims==null){
                log.error("解析token出现异常{}",token);
                return null;
            }
        }catch (Exception e){
            log.error("解析token出现异常",token,e);
            return null;
        }
        return JwtUtils.getUserKey(claims);
    }
    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}, 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}, 出现异常", token, e);
            return null;
        }
        return claims;
    }
    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    public void refreshLoginUser(String nickName, String headImage, String userkey) {
        String tokenKey=getTokenKey(userkey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey,loginUser);
    }
}


















